package com.example.gitzuoye3;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 电影排行榜Fragment，显示电影点击量排行
 * 实现OnDetailButtonClickListener接口以处理电影详情点击事件
 */
public class paihang extends Fragment implements com.example.gitzuoye3.shipeiqi.OnDetailButtonClickListener {

    private ListView paihangListView;  // 排行榜列表视图
    private com.example.gitzuoye3.shipeiqi adapter;          // 列表适配器
    private List<xiangxi.DianyingItem> paihangItems = new ArrayList<>(); // 排行数据
    private com.example.gitzuoye3.SQL sqlHelper;             // 数据库帮助类

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.paihang, container, false);
        paihangListView = view.findViewById(R.id.paihang_list);

        // 初始化数据库帮助类
        sqlHelper = new com.example.gitzuoye3.SQL(requireActivity());

        // 初始化所有电影数据并设置点击次数为0
        initializeAllMovies();

        // 初始化适配器
        adapter = new com.example.gitzuoye3.shipeiqi(getActivity(), paihangItems, this);
        adapter.setFavoriteChangeListener(() -> refreshPaihangData());
        paihangListView.setAdapter(adapter);

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        // 每次返回页面时刷新排行数据
        refreshPaihangData();
    }

    /**
     * 初始化所有电影数据，确保数据库中有记录
     */
    private void initializeAllMovies() {
        SQLiteDatabase db = sqlHelper.getWritableDatabase();
        try {
            List<xiangxi.DianyingItem> allMovies = getAllMovies();
            for (xiangxi.DianyingItem movie : allMovies) {
                // 检查电影是否已存在记录
                Cursor cursor = db.query("movie_clicks",
                        new String[]{"movie_id"},
                        "movie_id=?",
                        new String[]{String.valueOf(movie.getId())},
                        null, null, null);

                if (!cursor.moveToFirst()) {
                    // 如果不存在，则插入初始记录
                    ContentValues values = new ContentValues();
                    values.put("movie_id", movie.getId());
                    values.put("click_count", 0);
                    db.insert("movie_clicks", null, values);
                }
                cursor.close();
            }
        } catch (Exception e) {
            Log.e("paihang", "初始化电影数据失败", e);
        } finally {
            db.close();
        }
    }

    /**
     * 刷新排行榜数据
     */
    private void refreshPaihangData() {
        paihangItems.clear();

        SQLiteDatabase db = sqlHelper.getWritableDatabase();
        Cursor cursor = null;
        try {
            // 查询所有电影，包括点击次数为0的，按点击量降序排列
            String query = "SELECT m.movie_id, IFNULL(mc.click_count, 0) as click_count " +
                    "FROM (SELECT 1 as movie_id UNION SELECT 2 UNION SELECT 3 UNION " +
                    "SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8) as m " +
                    "LEFT JOIN movie_clicks mc ON m.movie_id = mc.movie_id " +
                    "ORDER BY click_count DESC";

            cursor = db.rawQuery(query, null);

            // 遍历查询结果，构建排行数据
            while (cursor.moveToNext()) {
                int movieId = cursor.getInt(cursor.getColumnIndex("movie_id"));
                int clickCount = cursor.getInt(cursor.getColumnIndex("click_count"));

                xiangxi.DianyingItem item = findDianyingItemById(movieId);
                if (item != null) {
                    item.clickCount = clickCount;
                    paihangItems.add(item);
                }
            }

            adapter.notifyDataSetChanged();

            if (paihangItems.isEmpty()) {
                Toast.makeText(getActivity(), "暂无排行数据", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Log.e("paihang", "获取排行数据失败", e);
            Toast.makeText(getActivity(), "获取排行数据失败", Toast.LENGTH_LONG).show();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            db.close();
        }
    }

    /**
     * 获取所有电影列表
     * @return 包含所有电影信息的列表
     */
    private List<xiangxi.DianyingItem> getAllMovies() {
        List<xiangxi.DianyingItem> allMovies = new ArrayList<>();
        allMovies.add(new xiangxi.DianyingItem(1, "大话西游", "导演：刘镇伟\n主演：周星驰、朱茵、吴孟达、蓝洁瑛、莫文蔚等。", "dhxy"));
        allMovies.add(new xiangxi.DianyingItem(2, "哈利波特与凤凰社", "导演：大卫·叶斯\n主演：丹尼尔·雷德克里夫、爱玛·沃森、鲁伯特·格林特等。 ", "fhs"));
        allMovies.add(new xiangxi.DianyingItem(3, "千与千寻", "导演：宫崎骏\n主演：柊柊柊柊柊柊柊柊瑠瑠瑠瑠瑠瑠瑠瑠美、入野自由、夏木麻里等。", "qyqx"));
        allMovies.add(new xiangxi.DianyingItem(4, "热烈", "导演：大鹏\n主演：黄渤、王一博、刘敏涛、岳云鹏、小沈阳等。", "rl"));
        allMovies.add(new xiangxi.DianyingItem(5, "唐人街探案3", "导演：陈思诚\n主演：王宝强、刘昊然、长泽雅美，妻夫木聪，三浦友和，肖阳，邱泽，陈哲远，张子枫，程潇，尚语贤等。\"", "tt3"));
        allMovies.add(new xiangxi.DianyingItem(6, "我爱你", "导演：韩延\n主演：倪大红、惠英红", "wan"));
        allMovies.add(new xiangxi.DianyingItem(7, "一出好戏", "导演：黄渤\n主演：黄渤、王宝强、舒淇、张艺兴、于和伟、王迅等。", "ychx"));
        allMovies.add(new xiangxi.DianyingItem(8, "哪吒之魔童闹海", "导演：饺子\n主要配音：吕艳婷、囧囧囧囧囧囧囧囧森瑟夫、瀚墨、陈浩、绿绮等。", "nz"));
        return allMovies;
    }

    /**
     * 根据ID查找电影项
     * @param id 电影ID
     * @return 对应的电影项，找不到返回null
     */
    private xiangxi.DianyingItem findDianyingItemById(int id) {
        for (xiangxi.DianyingItem item : getAllMovies()) {
            if (item.getId() == id) {
                return item;
            }
        }
        return null;
    }

    /**
     * 实现OnDetailButtonClickListener接口方法
     * 处理电影详情按钮点击事件
     */
    @Override
    public void onDetailButtonClick(xiangxi.DianyingItem item) {
        try {
            // 更新点击次数
            updateClickCount(item.getId());

            // 打开电影详情Fragment
            getParentFragmentManager().beginTransaction()
                    .replace(R.id.dianying_list, com.example.gitzuoye3.dianyingxinxi.newInstance(item))
                    .addToBackStack(null)
                    .commit();
        } catch (Exception e) {
            Log.e("paihang", "打开电影详情失败", e);
        }
    }

    /**
     * 更新电影的点击次数
     * @param movieId 电影ID
     */
    private void updateClickCount(int movieId) {
        SQLiteDatabase db = sqlHelper.getWritableDatabase();
        Cursor cursor = null;
        try {
            cursor = db.query("movie_clicks",
                    new String[]{"click_count"},
                    "movie_id=?",
                    new String[]{String.valueOf(movieId)},
                    null, null, null);

            ContentValues values = new ContentValues();

            if (cursor.moveToFirst()) {
                // 如果已有记录，点击次数+1
                int currentCount = cursor.getInt(cursor.getColumnIndex("click_count"));
                values.put("click_count", currentCount + 1);
                db.update("movie_clicks", values, "movie_id=?", new String[]{String.valueOf(movieId)});
            } else {
                // 如果没有记录，创建新记录并设置点击次数为1
                values.put("movie_id", movieId);
                values.put("click_count", 1);
                db.insert("movie_clicks", null, values);
            }

            // 刷新排行数据
            refreshPaihangData();
        } catch (Exception e) {
            Log.e("paihang", "更新点击次数失败", e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            db.close();
        }
    }
}